package com.itany.mall.dao.impl;

import java.util.Collection;
import java.util.List;

import com.itany.mall.dao.OrderDetailDao;
import com.itany.mall.dao.mapper.OrderDetailRowMapper;
import com.itany.mall.entity.OrderDetail;
import com.itany.mall.factory.Component;
import com.itany.mall.jdbc.template.JDBCTemplate;

@Component
public class OrderDetailDaoImpl implements OrderDetailDao {

	@Override
	public void saveOrUpdateOrderDetails(Collection<OrderDetail> values) {
		for (OrderDetail od : values) {
			if (od.getId() == null) {
				insert(od);
				continue;
			}
			update(od);
		}
	}

	private void update(OrderDetail od) {
		StringBuffer sql = new StringBuffer();
		sql.append(" update t_order_detail set ");
		sql.append("     order_id = ?, ");
		sql.append("     product_id = ?, ");
		sql.append("     product_sum = ?, ");
		sql.append("     price = ?, ");
		sql.append("     user_id = ? ");
		sql.append(" where id = ? ");
		Object[] params = { od.getOrderId(), od.getProductId(), od.getProductSum(), od.getPrice(),
				od.getUserId(), od.getId() };
		new JDBCTemplate<Long, OrderDetail>().update(sql.toString(), params);
	}

	private void insert(OrderDetail od) {
		String sql = " insert into t_order_detail(order_id, product_id, product_sum, price, user_id) values (?, ?, ?, ?, ?) ";
		Object[] params = { od.getOrderId(), od.getProductId(), od.getProductSum(), od.getPrice(),
				od.getUserId() };
		new JDBCTemplate<Long, OrderDetail>().update(sql, params);
	}

	@Override
	public List<OrderDetail> selectByUserId(long userId) {
		OrderDetailRowMapper mapper = new OrderDetailRowMapper();
		String sql = mapper.selectSql() + " where u.id = ? ";
		return new JDBCTemplate<Long, OrderDetail>().query(sql, new Object[] { userId }, mapper);
	}

	@Override
	public List<OrderDetail> selectByOrderNum(String num) {
		OrderDetailRowMapper mapper = new OrderDetailRowMapper();
		String sql = mapper.selectSql() + " where o.order_num = ? ";
		return new JDBCTemplate<Long, OrderDetail>().query(sql, new Object[] { num }, mapper);
	}
}
